<template>
  <div class="trigger-wrapper relative w-full">
    <i-textarea :disabled="disabled" v-model="address" @focus="focus" @input="input" @clear="clear" ref="triggerWrapperRef" />
    <!-- 悬浮框 -->
    <div class="arco-trigger-content popup-container arco-select-dropdown" v-if="popupVisible && addressData.length > 0">
      <a-scrollbar style="height: 200px; overflow: auto">
        <ul class="arco-select-dropdown-list">
          <li class="arco-select-option" v-for="(item, index) in addressData" :key="index" @click="select(item)">
            <span class="arco-select-option-content flex items-end">
              <span class="span-title"><icon-location style="margin-right: 6px" />{{ item.title }}</span>
              <span class="span-district">{{ item.district }}</span>
            </span>
          </li>
        </ul>
      </a-scrollbar>
    </div>
  </div>
</template>
<script setup>
  import { ref } from 'vue'
  import { useVModel, onClickOutside } from '@vueuse/core'
  import { loadMapScript } from '@/utils/loadMap'
  import { useDebounceFn } from '@vueuse/core'
  import iTextarea from '@/views/order/short-order/components/i-textarea.vue'
  const emit = defineEmits(['update:modelValue', 'change', 'setFieldWarnStatus', 'blur'])
  const props = defineProps({
    modelValue: String,
    disabled: Boolean,
  })
  const address = useVModel(props, 'modelValue', emit)
  // 记录一次查询是否录入，方便失焦的时候做逻辑判断
  const _inputChange = ref(false)
  const popupVisible = ref(false)
  let autocomplete = null
  // 关键字查询
  const mapSearch = (keyword, callback) => {
    new Promise((resolve) => {
      if (!autocomplete) {
        loadMapScript().then(() => {
          autocomplete = new AMap.AutoComplete({
            city: '全国',
          })
          resolve()
        })
      } else {
        resolve()
      }
    }).then(() => {
      autocomplete.search(keyword, (status, res) => {
        if (status == 'complete') {
          const result = res.tips
            .filter((item) => item.location)
            .map((item) => {
              return {
                title: item.name,
                lnglat: [item.location.KL, item.location.kT],
                district: item.district,
                address: item.address instanceof Array ? '' : item.address,
              }
            })
          callback(result)
        } else if (status == 'no_data') {
          callback([])
        }
      })
    })
  }
  // 逆地址解析
  const mapGeocoderLocation = (lnglat, callback) => {
    const geocoder = new AMap.Geocoder()
    const point = new AMap.LngLat(...lnglat)
    geocoder.getAddress(point, (status, result) => {
      let address
      if (status === 'complete' && result.regeocode) {
        address = result.regeocode.formattedAddress
      } else {
        console.log('根据经纬度查询地址失败')
      }
      callback(address, result.regeocode)
    })
  }

  // 聚焦
  const focus = () => {
    popupVisible.value = true
    if (props.modelValue) {
      search(props.modelValue)
    }
  }
  // 失焦
  const triggerWrapperRef = ref()
  onClickOutside(triggerWrapperRef, () => {
    popupVisible.value = false
    // 当前录入了
    if (props.modelValue) {
      emit('blur')
    }
  })
  // 输入
  const input = useDebounceFn((val) => {
    _inputChange.value = true
    emit('change')
    search(val)
  }, 300)
  // 查询
  const addressData = ref([])
  const search = (val) => {
    if (val) {
      mapSearch(val, (tips) => {
        let options = tips.map((item) => {
          return {
            label: item.title,
            value: item.title,
            ...item,
          }
        })
        addressData.value = options
      })
    } else {
      addressData.value = []
    }
  }
  // 选择
  const select = (option) => {
    // 查询具体地址
    mapGeocoderLocation(option.lnglat, (address) => {
      emit('update:modelValue', address)
      emit('change', option.lnglat)
    })
    _inputChange.value = false
    // 关闭悬浮框
    popupVisible.value = false
  }
  // 清空
  const clear = () => {
    addressData.value = []
    emit('change')
  }
</script>
<style lang="less" scoped>
  .trigger-wrapper {
    .popup-container {
      width: 100%;
      position: absolute;
      left: 0;
      z-index: 10;
    }
  }
  .span-district {
    margin-left: 10px;
    color: #999;
    font-size: 12px;
  }
</style>
